<?php
namespace JsonRpc\Services;
use JsonRpc\Services\System\UserService;

/**
 * Created by PhpStorm.
 * User: kery
 * Date: 2017/4/10
 * Time: 11:19
 */
trait CommonService{
    public static function ping(){
        return 'OK';
    }

    public static function getInfoById($params){
        $model  = self::getBaseModel();

        $info = $model::find($params['id']);
        if($info){
            return $info->toArray();
        }
        return [];
    }

    public static function getInfoList($params = []){
        $clazz = self::getBaseModel();
        $model  = new $clazz();
        if($model->has_client){
            $user = UserService::getInfoById(['id'=>$params['curr_user_id']]);
            $model = $model->where('client_id', $user['client_id']);
        }

        if(isset($params['sortby']) || !empty($params['sortby'])){
            if(is_array($params['sortby'])){
                foreach ($params['sortby'] as $sortBy){
                    if(is_array($sortBy)){
                        $model = $model->orderBy($sortBy[0], $sortBy[1]);
                    }else{
                        $model = $model->orderBy($sortBy);
                    }
                }
            }else{
                $model = $model->orderBy($params['sortby']);
            }
        }

        //菜单数据控制
        if(isset($params['curr_menu_id'])){
            $rules = UserService::getMenuDataRule(['menu_id'=>$params['curr_menu_id'], 'user_id'=>$params['curr_user_id']]);
            if(!empty($rules)){
                if(is_array($rules)){
                    foreach ($rules as $rule){
                        $model = $model->whereRaw($rule);
                    }
                }else{
                    $model = $model->whereRaw($rules);
                }
            }
        }

        if(isset($params['page'])){
            $page = isset($params['page']) ? intval($params['page']) : 1;
            $rows = isset($params['rows']) ? intval($params['rows']) : 10;
            $total = $model->toBase()->getCountForPagination();
            $info = $model->forPage($page, $rows)->get(isset($params['select'])?$params['select']:['*']);

            if($info){
                $list = $info->toArray();
            }else{
                $list = [];
            }
            return ['total'=>$total, 'rows'=>$list];
        }

        $info = $model->get(isset($params['select'])?$params['select']:['*']);
        if($info){
            return $info->toArray();
        }
        return [];
    }
}